package com.itfreer.gather.main.fragment;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.itfreer.arcgis.layer.LayerLoader;
import com.itfreer.arcgis.utils.MapUtils;
import com.itfreer.file.path.FileUpload;
import com.itfreer.gather.R;
import com.itfreer.gis.config.BaseMapService;
import com.itfreer.gis.config.entity.BaseMapEntity;
import com.itfreer.gis.datasyn.entity.ProjectEntity;
import com.itfreer.gis.datasyn.sub.ProjectService;
import com.itfreer.ui.base.checkbox.CheckBox;
import com.itfreer.ui.base.TextView;

import java.io.File;
import java.util.List;

/**
 * 图层管理
 */
@SuppressLint("ValidFragment")
public class MapLayerFragment extends Fragment {

    private MapView mMapView;
    private View v;

    /**
     * 定义无参构造方法
     */
    public MapLayerFragment() {
    }

    /**
     * 定义带参的构造方法
     *
     * @param mapView
     */
    public MapLayerFragment(MapView mapView) {
        this.mMapView = mapView;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.main_fragment_map_layer, container, false);
        initFeatureLayers();
        initTpkLayers();

        // 空白处时，关闭当前对象
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MapLayerFragment.this.getActivity().getFragmentManager().popBackStack();
            }
        });

        return v;
    }

    /**
     * 加载feature图层
     */
    private void initFeatureLayers(){
        LinearLayout main_fragment_map_feature = (LinearLayout) v.findViewById(R.id.main_fragment_map_feature);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 80);
        layoutParams.setMargins(20, 8, 15, 8);

        //获取图层对象
        List<ProjectEntity> layers = ProjectService.instance.getProject();
        if(layers != null && layers.size() >= 1){
            for (int i = 0; i < layers.size(); i++) {
                //获取相对布局
                RelativeLayout newSingleRL = getFeatureItem(layers.get(i));
                //添加RelativeLayout
                main_fragment_map_feature.addView(newSingleRL, 2 + (i * 2), layoutParams);//全部用父结点的布局参数

                //添加View
                View v1 = new View(getActivity());
                LinearLayout.LayoutParams vPm = new LinearLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, 1);
                v1.setBackground(new ColorDrawable(Color.parseColor("#FFDDDDDD")));
                v1.setLayoutParams(vPm);
                main_fragment_map_feature.addView(v1, 3 + (i * 2), vPm);
            }
        }
    }

    /**
     * 获取相对布局
     *
     * @param entity 业务图层实体
     * @return
     */
    private RelativeLayout getFeatureItem(ProjectEntity entity) {
        RelativeLayout layout_root_relative = new RelativeLayout(getActivity());

        //添加TextView控件
        TextView tv = new TextView(getActivity());
        RelativeLayout.LayoutParams tvPm = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        tvPm.setMargins(15, 0, 0, 0);
        tvPm.addRule(RelativeLayout.CENTER_VERTICAL);
        tv.setText(entity.getLayerName());
        tv.setTextColor(Color.parseColor("#FF303059"));
        tv.setTextSize(15);
        tv.setHeight(40);
        tv.setGravity(Gravity.CENTER|Gravity.LEFT);
        tv.setLayoutParams(tvPm);
        layout_root_relative.addView(tv);

        //添加checkbox按钮
        CheckBox cb = new CheckBox(getActivity());
        RelativeLayout.LayoutParams cbPm = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        cbPm.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        cbPm.addRule(RelativeLayout.CENTER_VERTICAL);
        cb.setTextColor(Color.parseColor("#FF303059"));
        cb.setChecked(entity.getShow());
        cb.setFieldName(entity.getId());
        cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                CheckBox cbl = (CheckBox) buttonView;
                //获取图层对象id值
                String id = cbl.getFieldName();
                //根据id获取本地图层数据实体
                ProjectEntity entity = ProjectService.instance.getProjectById(id);
                if (null != entity) {
                    //更新本地数据库
                    if (isChecked != entity.getShow()) {
                        entity.setShow(isChecked);
                    }
                    String name = getFileName(entity.getPath());
                    //获取图层对象
                    FeatureLayer featureLayer = MapUtils.GetFeatureLayerByName(mMapView, name);
                    if (null != featureLayer && featureLayer.canChangeVisibility()) {
                        featureLayer.setVisible(isChecked);
                    }

                    ProjectService.instance.updateProject(entity);
                    LayerLoader.instance.updateConfig(featureLayer, entity);
                }
            }
        });
        cb.setLayoutParams(cbPm);
        layout_root_relative.addView(cb);

        return layout_root_relative;
    }

    /**
     * 加载feature图层
     */
    private void initTpkLayers(){
        LinearLayout main_fragment_map_tpk = (LinearLayout) v.findViewById(R.id.main_fragment_map_tpk);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 80);
        layoutParams.setMargins(20, 8, 15, 8);

        //获取图层对象
        List<BaseMapEntity> baseMaps = BaseMapService.instance.getEntitys();
        int i = 0;
        for(BaseMapEntity item : baseMaps){
            if(!isDownload(item)){
                continue;
            }

            //获取相对布局
            RelativeLayout newSingleRL = getTpkItem(item);
            //添加RelativeLayout
            main_fragment_map_tpk.addView(newSingleRL, 2 + (i * 2), layoutParams);//全部用父结点的布局参数

            //添加View
            View v1 = new View(getActivity());
            LinearLayout.LayoutParams vPm = new LinearLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, 1);
            v1.setBackground(new ColorDrawable(Color.parseColor("#FFDDDDDD")));
            v1.setLayoutParams(vPm);
            main_fragment_map_tpk.addView(v1, 3 + (i * 2), vPm);
            i ++ ;
        }
    }

    /**
     * 获取相对布局
     *
     * @param entity 业务图层实体
     * @return
     */
    private RelativeLayout getTpkItem(BaseMapEntity entity) {
        RelativeLayout layout_root_relative = new RelativeLayout(getActivity());

        //添加TextView控件
        TextView tv = new TextView(getActivity());
        RelativeLayout.LayoutParams tvPm = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        tvPm.setMargins(15, 0, 0, 0);
        tvPm.addRule(RelativeLayout.CENTER_VERTICAL);
        tv.setText(entity.getName());
        tv.setTextColor(Color.parseColor("#FF303059"));
        tv.setTextSize(15);
        tv.setHeight(40);
        tv.setGravity(Gravity.CENTER|Gravity.LEFT);
        tv.setLayoutParams(tvPm);
        layout_root_relative.addView(tv);

        return layout_root_relative;
    }

    private boolean isDownload(BaseMapEntity item){
        String path = item.getPath();
        String[] paths = path.split(":");
        String buckt = paths[0];
        String key = paths[1];

        // 如果在，说明没有修改过，无需重新下载
        String file = FileUpload.instance.getFile(buckt, key);
        File zipFile = new File(file);
        return zipFile.exists();
    }

    /**
     * 获取文件名
     *
     * @return
     */
    private String getFileName(String path) {
        String[] paths = path.split(":");
        String fName = paths[2];
        fName = fName.replace(".zip", "").replace(".ZIP", "");
        return fName;
    }
}

